package com.wxp.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.models.constant.JafCoreConstant;
import com.models.constant.MessageConstant;
import com.modules.annotation.MenuMapping;
import com.modules.annotation.ResourceMapping;
import com.modules.annotation.ResourceMapping.Operation;
import com.modules.persistence.DynamicSpecifications;
import com.modules.web.CRUDController;
import com.wxp.entity.Role;
import com.wxp.entity.User;
import com.wxp.service.RoleService;
import com.wxp.service.UserService;

@Controller
@RequestMapping("/user/userInfo")
@MenuMapping(name = "用户信息", operator = "user10", parentOperator = "larry")
public class UserController extends CRUDController{
    private static Logger logger	= LoggerFactory.getLogger(UserController.class);

    /***
    
     * 
     * 同时注意  operator中的所有值都是作为主键进行存在的，不能够重复存在
     * 这样设置免去了  菜单的相关配置
     * */
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private RoleService roleService;

    @RequestMapping("/list")
    @RequiresPermissions ("user:list")//权限
    @ResourceMapping(name = "用户列表", operation = Operation.MENU)
    public String list(Model model){

        return "user/userList";
    }
    /*
     * 这个查询是跟页面按钮相关的操作是一个层级的
     * RequiresPermissions为了进行权限控制
     * **/
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @RequiresPermissions ("user:list")//权限
    @ResponseBody
    public Map<String, Object> query(HttpServletRequest request) throws Exception {

        Page page = onPrepareQueryData(request);
        return  transferTo(page);
    }
    
    protected Page onPrepareQueryData(HttpServletRequest request) throws Exception {
    	Specification spec = DynamicSpecifications.bySearchFilter(request);//查询条件(基本查询条件)
    	//Specification spec = DynamicSpecifications.bySearchFilter(request,DynamicSpecifications.bulidSearchSpecFilter(new SearchFilter("EQ_name","王鹏"),new SearchFilter("or","EQ_name","撒地方")));//查询条件(基本查询条件)
        PageRequest pageRequest = DynamicSpecifications.buildPageRequest(request,null);//相关的分页
        Page<User> page = userService.findAll(spec,pageRequest);
        return page;//用来查询相关的数据
    }

    @RequiresPermissions ("user:add")//权限
    @ResourceMapping(name = "添加用户", operation = Operation.BUTTON)
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String showAddPage(Model model) {

        return "user/userEdit";
    }
    
    @RequiresPermissions ("user:view")//权限
    @ResourceMapping(name = "用户信息查看", operation = Operation.BUTTON)
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String showViewPage(String id,  Model model) {
        //return "user/userView";
    	 return "user/userEdit";
    }

    /**
     * 返回编辑页面
     * @param id
     * @return 编辑页面
     */
    @RequiresPermissions ("user:edit")
    @ResourceMapping(name = "用户信息编辑页面", operation = Operation.BUTTON)
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String showEditPage(String id,  Model model) {
        return "user/userEdit";
    }


    /**
     * 获取指定primary key的实体对象（数据库记录）
     */
    @RequiresPermissions (value={"user:edit","user:add","user:view"},logical=Logical.OR)//权限跟其先关的操作是一样的
    @RequestMapping(value = "/edit/{id}")
    @ResponseBody
    public User getEditData(@PathVariable String id) {
        User user = null;
        try {
            user = userService.get(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }
    /**
     * 保存是作为新建和编辑按钮的辅助性操作，可以认为保存是新建和保存下的子操作
     * 辅助操作的权限不用进行显示
     * */
    @RequiresPermissions (value={"user:edit", "user:add"},logical=Logical.OR)
    @RequestMapping(value = "/save")
    @ResponseBody
    public Map<String, Object> save(User user) {
        Map<String, Object> tips = new HashMap<String, Object>();
        try {
			String result = userService.saveUser(user);
			//如果需要在不关闭窗口的情况下多次更新，则需要向页面回写version，打开下面的代码
			if (JafCoreConstant.OUT_OF_DATE.equals(result)){
				tips.put(MessageConstant.SUCCESS, false);
				tips.put(MessageConstant.MSG, MessageConstant.FAILURE_OUT_OF_DATE);
			}else{
				tips.put(MessageConstant.SUCCESS, true);
				tips.put(MessageConstant.MSG, MessageConstant.SUCCESS_SAVE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			tips.put(MessageConstant.SUCCESS, false);
			tips.put(MessageConstant.MSG, MessageConstant.FAILURE_SAVE);
		}
        return tips;
    }
    
    
    @RequiresPermissions ("user:delete")//权限跟其先关的操作是一样的
    @RequestMapping(value = "/delete/{id}")
    @ResourceMapping(name = "用户信息删除", operation = Operation.BUTTON)
    @ResponseBody
    public Map<String,Object> delete(@PathVariable String id){
    	Map<String,Object> tips = new HashMap<String, Object>();
        try {
           userService.deleteUser(id);
    	   tips.put(MessageConstant.SUCCESS, true);
		   tips.put(MessageConstant.MSG, MessageConstant.SUCCESS_DELETE);
        }catch (Exception e) {
    	   e.printStackTrace();
    	   tips.put(MessageConstant.SUCCESS, false);
		   tips.put(MessageConstant.MSG, MessageConstant.FAILURE_DELETE);
        }
    	return tips;
    }
    
    
    @RequiresPermissions ("user:userrole")
    @RequestMapping(value = "/userRoleAdd")
    @ResourceMapping(name = "设置用户角色信息", operation = Operation.BUTTON)
    public String addUserRole() {
    	return "user/userRoleAdd";
    }
    
    
    @RequiresPermissions ("user:userrole")
    @RequestMapping(value = "/saveUserRole")
    @ResponseBody
    public Map<String,Object>  saveUserRole(String userId,String data){
    	Map<String,Object> tips = new HashMap<String, Object>();
        try {
           userService.saveUserRole(userId, data);
    	   tips.put(MessageConstant.SUCCESS, true);
		   tips.put(MessageConstant.MSG, MessageConstant.SUCCESS_SAVE);
        }catch (Exception e) {
    	   e.printStackTrace();
    	   tips.put(MessageConstant.SUCCESS, false);
		   tips.put(MessageConstant.MSG, MessageConstant.FAILURE_SAVE);
        }
    	return tips;
    }
    
    
    //查找用户的角色
    @RequiresPermissions ("user:userrole")
    @RequestMapping(value = "/findUserRole", method = RequestMethod.POST)
    @ResponseBody
    public List<Role> findUserRoleAll(String userId){
    	List<Role> roleList = roleService.findUserRoleAll(userId);
    	return roleList;
    }
    
}
